package user

import (
	"errors"
	"gitee.com/gopher2011/go-zero-gva/internal/logic/base"
	"gitee.com/gopher2011/go-zero-gva/internal/svc"
	"gitee.com/gopher2011/go-zero-gva/internal/types"
	"github.com/satori/go.uuid"
	"gorm.io/gorm"
	"net/http"
	"strconv"
)

func (l *User) SetUserAuthority(id uint, uuid uuid.UUID, authorityId string,claims *svc.CustomClaims,r *http.Request) (*types.Response, error) {
	if errors.Is(l.SvcCtx.DB.Where("sys_user_id = ? AND sys_authority_authority_id = ?",id,authorityId).First(&svc.SysUserAuthority{}).Error,gorm.ErrRecordNotFound) {
		return &types.Response{
			Code: 7,
			Msg: "该用户无此角色",
		}, nil
	}
	// 这里有两条 sql 语句
	// select * from sys_user where uuid = ? limit 1
	// update sys_user set authority_id = ? where uuid = ?
	if err := l.SvcCtx.DB.Where("uuid = ?",uuid).First(&svc.SysUser{}).Update("authority_id", authorityId).Error;err !=nil {
		return &types.Response{
			Code: 7,
			Msg: err.Error(),
		}, nil
	}
	claims.AuthorityId = authorityId
	if token,err := base.NewBase(l.Ctx,l.SvcCtx).CreateToken(*claims);err !=nil {
		return &types.Response{
			Code: 7,
			Msg: err.Error(),
		}, nil
	}else {
		r.Header.Set("new-token",token)
		r.Header.Set("nex-expires-at",strconv.FormatInt(claims.ExpiresAt,10))
		return &types.Response{
			Code: 0,
			Msg: "修改成功",
		}, nil
	}
}
